<template>
<div class="sidebar">
    <el-tree style="max-width: 600px" indent="10" :data="menu" :props="defaultProps"  @node-click="handleNodeClick"/>
</div>
</template>

<script setup>
import {onMounted,ref} from 'vue';
import {useRouter} from 'vue-router';
import {getMenu} from '@/api/sys/menu'

const router = useRouter();
let Module = import.meta.glob("@/views/**/*.vue");

const handleNodeClick = (data) => {
  if(data.type=='C')
    router.push(data.path)
}

//加载组件
function loadComponent(url) {
  let path = Module[`/src/views/${url}.vue`];
  return path;
}

const menu = ref([]);

const defaultProps = {
  children: 'children',
  label: 'name',
}



const addMenu = (menu)=>{
  menu.forEach(item=>{

    if(item.type=='C'){
      let ret = {
        name: item.name,
        path: item.path,
        component: loadComponent(item.component)
      }
      
      if(typeof ret.component == 'undefined'){
        console.error("组件"+item.component+"不存在")
        ret.component = loadComponent('404')
      }
      
      router.addRoute(item.name, ret)

    }

    if(item.children && item.children.length>0){
      addMenu(item.children)
    }
  })
}

onMounted(() => {
  getMenu().then(res=>{
    menu.value = res.data;
    addMenu(menu.value);

  })
})

</script>

<style scoped>
.sidebar{
  height:calc( 100vh - 60px );
  background-color:white;
  padding-top:10px;
}

</style>